import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
import { useEffect, useState } from 'react'
import './App.css'
import { AuthProvider } from './contexts/AuthContext'
import HomePage from './pages/HomePage'
import DrawingPage from './pages/DrawingPage'
import SavedDrawingsPage from './pages/SavedDrawingsPage'
import LoginPage from './pages/LoginPage'
import RegisterPage from './pages/RegisterPage'
import ChangePasswordPage from './pages/ChangePasswordPage'
import LeaderboardPage from './pages/LeaderboardPage'

function App() {
  // 全局：移动端/平板纵向时提示横屏，并尽力锁定横屏
  const [isPortraitMobile, setIsPortraitMobile] = useState(false)
  const [orientationError, setOrientationError] = useState('')

  useEffect(() => {
    // 初始化主题
    const savedTheme = localStorage.getItem('theme') || 'light'
    document.documentElement.setAttribute('data-theme', savedTheme)
  }, [])

  useEffect(() => {
    const update = () => {
      const isMobile = window.innerWidth < 1024
      const isPortrait = window.innerHeight > window.innerWidth
      setIsPortraitMobile(isMobile && isPortrait)
    }
    update()
    window.addEventListener('resize', update)
    window.addEventListener('orientationchange', update as any)
    return () => {
      window.removeEventListener('resize', update)
      window.removeEventListener('orientationchange', update as any)
    }
  }, [])

  useEffect(() => {
    // 尝试默认锁定横屏（部分浏览器需要用户手势，失败则仅提示）
    const isMobile = window.innerWidth < 1024
    if (!isMobile) return
    const tryLock = async () => {
      try {
        const anyScreen: any = screen as any
        if (anyScreen.orientation?.lock) {
          await anyScreen.orientation.lock('landscape')
          setOrientationError('')
        }
      } catch (e) {
        setOrientationError((e as Error)?.message || '无法锁定横屏')
      }
    }
    tryLock()
  }, [])

  const requestFullscreenAndLock = async () => {
    try {
      const el: any = document.documentElement as any
      if (el.requestFullscreen) {
        await el.requestFullscreen()
      } else if (el.webkitRequestFullscreen) {
        await el.webkitRequestFullscreen()
      }
      const anyScreen: any = screen as any
      if (anyScreen.orientation?.lock) {
        await anyScreen.orientation.lock('landscape')
      }
      setOrientationError('')
    } catch (e) {
      setOrientationError((e as Error)?.message || '无法锁定横屏')
    }
  }

  return (
    <AuthProvider>
      {/* 全局提示：移动端纵向时显示遮罩，引导横屏或授权横屏 */}
      {isPortraitMobile && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-base-200/95 backdrop-blur-sm">
          <div className="text-center">
            <div className="text-5xl mb-4">🔄</div>
            <p className="text-lg font-medium">为获得最佳体验，请将设备横屏</p>
            <p className="text-sm opacity-70 mt-2">或点击下方按钮尝试授权横屏</p>
            <button className="btn btn-primary mt-4" onClick={requestFullscreenAndLock}>
              授权横屏
            </button>
            {orientationError && (
              <p className="text-xs mt-2 opacity-60">{orientationError}</p>
            )}
          </div>
        </div>
      )}

      <Router future={{ v7_startTransition: true, v7_relativeSplatPath: true }}>
        <Routes>
          <Route path="/" element={<HomePage />} />
          <Route path="/draw" element={<DrawingPage />} />
          <Route path="/saved" element={<SavedDrawingsPage />} />
          <Route path="/login" element={<LoginPage />} />
          <Route path="/register" element={<RegisterPage />} />
          <Route path="/change-password" element={<ChangePasswordPage />} />
          <Route path="/leaderboard" element={<LeaderboardPage />} />
        </Routes>
      </Router>
    </AuthProvider>
  )
}

export default App
